package com.xywl.escort.view.setting

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.text.Html
import android.text.TextUtils
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.sdk.android.push.CommonCallback
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory
import com.raizlabs.android.dbflow.sql.language.Delete
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.NmApplication
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.BaseResp
import com.xywl.escort.bean.MessageEvent
import com.xywl.escort.bean.UpgradeResp
import com.xywl.escort.common.Constant
import com.xywl.escort.common.PreferenceKeys.*
import com.xywl.escort.db.SearchModel
import com.xywl.escort.utils.DataCleanManager
import com.xywl.escort.utils.RxSPTool
import com.xywl.escort.utils.TelephonyUtil
import com.xywl.escort.utils.ToastUtil
import com.xywl.escort.widget.CustomDialog
import com.xywl.escort.widget.UpgradeDialog
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_settings.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import timber.log.Timber
import javax.inject.Inject

@Route(path = "/xy/setting")
class SettingsActivity : BaseActivity(), SettingsContract.View {

    @Inject
    lateinit var mPresenter: SettingsContract.Presenter
    private var mDialog: CustomDialog? = null
    private var mUpgradeDialog: UpgradeDialog? = null
    private val MSG_LOAD_DATA = 0x0001

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_settings)
        showBackButton()
        setTitleText(R.string.setting)

        addListener()
        EventBus.getDefault().register(this)
    }

    private fun addListener() {
        text_modify_pwd.setOnClickListener {
            val token = RxSPTool.getString(this, TOKEN)
            if (!TextUtils.isEmpty(token)) {
                ARouter.getInstance().build("/xy/pwd/modify").navigation()
            } else {
                ARouter.getInstance().build("/xy/login").navigation()
            }
        }
        text_modify_pay_pwd.setOnClickListener {
            val token = RxSPTool.getString(this, TOKEN)
            if (!TextUtils.isEmpty(token)) {
                val userId = RxSPTool.getString(this, USER_ID)
                mPresenter.isSetPayPwd(userId)
            } else {
                ARouter.getInstance().build("/xy/login").navigation()
            }
        }
        text_contact_us.setOnClickListener {
            ARouter.getInstance().build("/xy/setting/contact").navigation()
        }
        text_dev.setOnClickListener {
            ARouter.getInstance().build("/xy/dev").navigation()
        }

        text_clear_cache.setOnClickListener {
            DataCleanManager.getInstance().clearAllCache(this)
            Delete.table(SearchModel::class.java)

            mHandler.sendEmptyMessageDelayed(MSG_LOAD_DATA, 1000)
        }

        layout_version.setOnClickListener {
            val versionCode = getVersionCode()
            // 【必传】1:安卓 2:IOS
            mPresenter.upgrade(1, versionCode, 2)
        }

        text_exit.setOnClickListener {
            mDialog = CustomDialog.Builder(this)
                    .setMessage("您确认要退出农门标局吗?")
                    .setNegativeButton(R.string.setting_confirm,
                            R.drawable.button_dialog_transparent, R.color.main_body_major_color) { _, _ ->
                        val token = RxSPTool.getString(this, TOKEN)
                        val deviceId = RxSPTool.getString(this, DEVICE_ID)
                        mPresenter.userExit(token, deviceId)
                        mDialog!!.dismiss()
                    }.setPositiveButton(R.string.setting_cancel, R.drawable.button_dialog_green, android.R.color.white, null).create()
            mDialog!!.show()
        }
    }

    private val mHandler = Handler(Handler.Callback { message ->
        when (message.what) {
            MSG_LOAD_DATA -> {
                ToastUtil.showTip(this, "清除成功")
            }
        }
        false
    })

    private fun clearUserInfo() {
        RxSPTool.clearPreference(this, USER_ID)
        RxSPTool.clearPreference(this, TOKEN)
        RxSPTool.clearPreference(this, PHONE)
        RxSPTool.clearPreference(this, NICK_NAME)
        RxSPTool.clearPreference(this, HEAD_IMG)
    }

    public override fun onResume() {
        super.onResume()
        val isDev = RxSPTool.getBoolean(this@SettingsActivity, IS_DEV)
        if (isDev) {
            text_dev.visibility = View.VISIBLE
        } else {
            text_dev.visibility = View.GONE
        }
        val token = RxSPTool.getString(this, TOKEN)
        if (!TextUtils.isEmpty(token)) {
            text_exit.visibility = View.VISIBLE
        } else {
            text_exit.visibility = View.GONE
        }

        mPresenter.takeView(this)
        val versionCode = getVersionCode()
        // 【必传】1:安卓 2:IOS
        mPresenter.upgrade(1, versionCode, 1)
    }

    private fun getVersionCode(): Int {
        val packageInfo = TelephonyUtil.getAppVersionCode(applicationContext)
        var versionCode = 0
        if (null != packageInfo) {
            versionCode = packageInfo.versionCode
        }
        return versionCode
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun mainEventBus(event: MessageEvent) {
        Timber.tag("SettingsActivity").e("event.message=" + event.message)
        Timber.tag("SettingsActivity").e("event.type=" + event.type)
        when (event.type) {
            Constant.EventType.EVENT_MODIFY_LOGIN_PWD_TYPE -> {
                val message = event.message
                if (!TextUtils.isEmpty(message)) {
                    if (message == Constant.EventMessage.FINISH_ACTIVITY) {
                        finish()
                    }
                }
            }
            else -> {
            }
        }
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun hasSetPayPwd() {
        ARouter.getInstance().build("/xy/pwd/modify/pay").navigation()
    }

    override fun noSetPayPwd() {
        ARouter.getInstance().build("/xy/pwd/setting/pay").navigation()
    }

    override fun hasUpgrade(dataBean: UpgradeResp.DataBean?) {
        val msg = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            Html.fromHtml(dataBean!!.versionDescribe, Html.FROM_HTML_MODE_LEGACY).toString()
        } else {
            Html.fromHtml(dataBean!!.versionDescribe).toString()
        }
        if (dataBean.isCompulsoryUpdate == 2) {
            mUpgradeDialog = UpgradeDialog.Builder(this)
                    .setMessage(msg)
                    .setPositiveButton(R.string.go_update, R.drawable.button_dialog_green, R.color.white) { _, _ ->
                        val intent = Intent()
                        intent.action = "android.intent.action.VIEW"
                        var url = dataBean.appUrl
                        if (!url.startsWith("https://") && !url.startsWith("http://")) {
                            url = "http://$url"
                        }
                        intent.data = Uri.parse(url)
                        startActivity(intent)
                    }.setCloseButton { _, _ ->
                        mUpgradeDialog!!.dismiss()
                        NmApplication.getInstance().finishAllActivity()
                        finish()
                    }.create()
            mUpgradeDialog!!.setCancelable(false)
            mUpgradeDialog!!.show()
        } else {
            mUpgradeDialog = UpgradeDialog.Builder(this)
                    .setMessage(msg)
                    .setPositiveButton(R.string.go_update, R.drawable.button_dialog_green, R.color.white) { _, _ ->
                        mUpgradeDialog!!.dismiss()
                        val intent = Intent()
                        intent.action = "android.intent.action.VIEW"
                        var url = dataBean.appUrl
                        if (!url.startsWith("https://") && !url.startsWith("http://")) {
                            url = "http://$url"
                        }
                        intent.data = Uri.parse(url)
                        startActivity(intent)
                    }.setCloseButton { _, _ ->
                        mUpgradeDialog!!.dismiss()
                    }.create()
            mUpgradeDialog!!.show()
        }
    }

    override fun noUpgrade(msg: String, type: Int) {
        if (type == 1) {
            text_version_value.text = "已是最新版"
        } else {
            ToastUtil.showTip(this, msg)
        }
    }

    override fun findIsFitPayPwdFailure(msg: String?) {
        ToastUtil.showTip(this, msg)
    }

    override fun userExitSuccess(resp: BaseResp?) {
        val pushService = PushServiceFactory.getCloudPushService()
        pushService.unbindAccount(object : CommonCallback {
            override fun onSuccess(response: String) {
                Timber.e("unbindAccount response=$response")
            }

            override fun onFailed(errorCode: String, errorMessage: String) {
                Timber.e("unbindAccount failed -- errorCode:$errorCode -- errorMessage:$errorMessage")
            }
        })
        clearUserInfo()
        finish()
    }

    override fun userExitFailure() {
        val pushService = PushServiceFactory.getCloudPushService()
        pushService.unbindAccount(object : CommonCallback {
            override fun onSuccess(response: String) {
                Timber.e("unbindAccount response=$response")
            }

            override fun onFailed(errorCode: String, errorMessage: String) {
                Timber.e("unbindAccount failed -- errorCode:$errorCode -- errorMessage:$errorMessage")
            }
        })
        clearUserInfo()
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        mDialog?.let {
            mDialog!!.dismiss()
        }
        mUpgradeDialog?.let {
            mUpgradeDialog!!.dismiss()
        }
        EventBus.getDefault().unregister(this)
    }
}
